<?php
/**
 * 定时任务脚本 - 刷新客户业务数据
 *
 * 此脚本用于在定时任务中自动刷新客户表中的业务字段数据
 * 作为触发器的替代方案，建议每天凌晨2点执行
 *
 * 使用方法：
 * 1. 命令行执行：php refresh_business_data.php
 * 2. 添加到crontab（推荐）：
 *    0 2 * * * /usr/bin/php /path/to/your/project/backend/database/optimization/refresh_business_data.php
 */

echo "==========================================\n";
echo "  客户业务数据刷新任务\n";
echo "  " . date('Y-m-d H:i:s') . "\n";
echo "==========================================\n\n";

// 引入自动加载
require dirname(__DIR__, 2) . '/vendor/autoload.php';

// 初始化ThinkPHP应用
$app = new \think\App();
$app->initialize();

try {
    // 创建Customer模型实例
    $customerModel = new \app\model\customer\Customer();

    echo "1. 开始刷新业务数据...\n";

    // 执行数据刷新
    $startTime = microtime(true);
    $success = $customerModel->refreshAllBusinessData();
    $duration = microtime(true) - $startTime;

    if ($success) {
        echo "   ✓ 数据刷新完成\n";
        echo "   耗时: " . number_format($duration, 2) . " 秒\n\n";

        // 验证刷新结果
        echo "2. 验证刷新结果...\n";
        $pdo = new PDO('mysql:host=localhost;dbname=oa5;charset=utf8mb4', 'root', '123456');
        $stmt = $pdo->query("
            SELECT id, name, is_member, contract_num, contract_amount, case_num
            FROM oa_customer
            WHERE delete_time = 0 AND discard_time = 0
            ORDER BY id DESC
            LIMIT 1
        ");
        $sample = $stmt->fetch();
        if ($sample) {
            echo "   样本客户: {$sample['name']}\n";
            echo "   会员状态: " . ($sample['is_member'] ? '是' : '否') . "\n";
            echo "   合同数量: {$sample['contract_num']}\n";
            echo "   合同金额: ¥" . number_format($sample['contract_amount'], 0) . "\n";
            echo "   案件数量: {$sample['case_num']}\n\n";
        }

        echo "==========================================\n";
        echo "  任务执行成功！\n";
        echo "==========================================\n\n";

        // 记录到日志（可选）
        $logFile = __DIR__ . '/refresh_log.txt';
        $logMessage = date('Y-m-d H:i:s') . " - 数据刷新成功，耗时: " . number_format($duration, 2) . " 秒\n";
        file_put_contents($logFile, $logMessage, FILE_APPEND | LOCK_EX);

        exit(0);
    } else {
        throw new Exception("数据刷新失败");
    }

} catch (Exception $e) {
    echo "   ✗ 任务执行失败: " . $e->getMessage() . "\n\n";

    // 记录错误日志
    $logFile = __DIR__ . '/refresh_error_log.txt';
    $logMessage = date('Y-m-d H:i:s') . " - 错误: " . $e->getMessage() . "\n";
    file_put_contents($logFile, $logMessage, FILE_APPEND | LOCK_EX);

    echo "错误详情已记录到: $logFile\n\n";
    exit(1);
}
